package com.usian.comment.service.impl

import com.usian.comment.feign.UserFeign
import com.usian.comment.service.CommentService
import com.usian.common.aliyun.GreenImageScan
import com.usian.model.comment.dtos.CommentDto
import com.usian.model.comment.dtos.CommentLikeDto
import com.usian.model.comment.dtos.CommentSaveDto
import com.usian.model.comment.pojos.ApComment
import com.usian.model.comment.pojos.ApCommentLike
import com.usian.model.comment.vo.ApCommentVo
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.utils.threadlocal.AppThreadLocalUtils
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.util.*
import javax.xml.ws.Response
import kotlin.collections.HashMap

@Service
class CommentServiceImpl : CommentService {
    @Autowired
    lateinit var mongoTemplate: MongoTemplate
    @Autowired
    lateinit var userFeign: UserFeign
    @Autowired
    lateinit var textScan: GreenImageScan

    override fun saveComment(dto: CommentSaveDto): ResponseResult<*> {
        if (dto.articleId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)
        if (dto.content != null && dto.content.length > 140) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字")
        //判断用户是否登录
        val userid = AppThreadLocalUtils.getUser().id
        if (userid == null) ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)
        //3.安全过滤

        //4.保存评论
        var apUser = userFeign.findUserById(userid)
        mongoTemplate.insert(ApComment().apply {
            authorId = apUser.id
            authorName = apUser.name
            content = dto.content
            entryId = dto.articleId
            createdTime = Date()
            updatedTime = Date()
            image = apUser.image
            likes = 0
            reply = 0
            type = 0
            flag = 0
        })


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS)

    }

    override fun like(dto: CommentLikeDto): ResponseResult<*> {
        //1检查参数
        if (dto.commentId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)
        //2.判断是否登录
        val userId = AppThreadLocalUtils.getUser().id
        if (userId == null) ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)

        val apUser = userFeign.findUserById(userId)
        //3.点赞操作
        val apComment = mongoTemplate.findById(dto.commentId, ApComment::class.java)
        if (apComment != null && dto.operation == 0.toShort()) {
            //更新评论的点赞数量
            apComment.likes = apComment.likes + 1
            mongoTemplate.save(apComment)
            //保存APP评论信息点赞
            mongoTemplate.insert(ApCommentLike().apply {
                authorId = apUser.id
                commentId = apComment.id
                operation = dto.operation

            })
        } else if (apComment != null && dto.operation == 1.toShort()) {
            //4.取消点赞
            //更新评论的点赞数量
            apComment.likes = if (apComment.likes < 0) 0 else apComment.likes - 1
            mongoTemplate.save(apComment)
            //删除记录
            mongoTemplate.remove(Query.query(Criteria.where("authorId").`is`(userId).and("commentId").`is`(apComment.id)), ApCommentLike::class.java)
        }
        //5.数据返回
        var mutableMap: MutableMap<String, Any> = mutableMapOf("likes" to apComment.likes)
        return ResponseResult.okResult(mutableMap)
    }

    override fun findByArticleId(dto: CommentDto): ResponseResult<*> {
        //1.检查参数
        if (dto.articleId == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE)

        val size : Int = 10
        //2.按照文章id过滤，设置分页和排序
        val list = mongoTemplate.find(Query.query(Criteria.where("entryId").`is`(dto.articleId).and("createdTime").lt(dto.minDate)).limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApComment::class.java)
        //3.数据封装返回
        //3.1用户未登录 加载数据
        val userId = AppThreadLocalUtils.getUser().id
        if (userId == null) ResponseResult.okResult(list)
        //3.2 用户已登录，加载数据，需要判断当前用户点赞了哪些评论
        var idList = list.map {
            it.id
        }
        var quey = mongoTemplate.find(Query.query(Criteria.where("commentId").`in`(idList).and("authorId").`is`(userId)), ApCommentLike::class.java)
        var conmmentList: MutableList<ApCommentVo> = arrayListOf()

        if (list != null && quey != null) {
            list.forEach {
                conmmentList.add(ApCommentVo().apply {
                    BeanUtils.copyProperties(it, this)
                    for (apCommentLike in quey) {
                        if (it.id == apCommentLike.commentId) {
                            this.operation = 0
                            break
                        }
                    }

                })
            }

            return ResponseResult.okResult(conmmentList)
        } else {
            return ResponseResult.okResult(list)
        }
    }

}